package logic

import (
	"context"
	"gitee.com/Cauchy_AQ/vxopen/model/mongodb"
	redis2 "gitee.com/Cauchy_AQ/vxopen/model/redis"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/errors"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"
	"gitee.com/Cauchy_AQ/vxopen/utils"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *transform.UserOptReq) (*transform.UserOptResp, error) {
	// 1. 校验验证码是否正确
	if !VerifyCaptcha(in.Key, in.Code) {
		return nil, errors.ErrorVerifyCaptcha
	}
	// 2. 检查用户是否存在
	mongoClient := mongodb.GetMongoInstance(l.svcCtx.Config.ModelConfig)
	user, err := mongoClient.UserCol.FindOneByMobile(context.Background(), in.Mobile)
	if err != nil && err != mongodb.ErrNotFound {
		return nil, err
	}
	if user != nil {
		return nil, errors.ErrorUserExist
	}

	// 3. 构建用户结构
	usernew := &mongodb.User{
		OpenID:        "",
		SubscribeTime: 0,
		Mobile:        in.Mobile,
		Password:      utils.EncryptPassword(in.Passwd),
		Name:          in.Mobile,
		Avatar:        "",
		VX:            "",
		QQ:            "",
		Desc:          "",
	}
	// 4. 查询用户角色信息
	role, err := mongoClient.RoleCol.FindOneByName(context.Background(), "普通用户")
	if err != nil && err != mongodb.ErrNotFound {
		return nil, err
	}
	if role == nil {
		return nil, errors.ErrorRoleNotExist
	}
	usernew.Role = *role

	// 5. 插入用户
	if err := mongoClient.UserCol.InsertByMobile(context.Background(), usernew); err != nil {
		return nil, err
	}

	// 6. 注册成功
	key := redis2.CacheNewUsersPrefix + utils.GetMonth(time.Now())
	// 就不去判exists了，因为过月自然不访问当前变量了
	_, _ = l.svcCtx.RDB.Incr(context.Background(), key).Result()
	_, _ = l.svcCtx.RDB.Expire(context.Background(), key, redis2.CacheNewUsersPrefixTimeout).Result()

	return &transform.UserOptResp{}, nil
}
